import { Image, InfiniteScroll, List } from 'antd-mobile'
import { useEffect, useState } from "react"
import { fetchArticleListAPI } from "@/apis/list"
import type { ListRes } from '@/apis/list'
import { useNavigate } from 'react-router-dom'

type Props = {
  channelId: string,
}

// 获取列表数据
const HomeList = (props: Props) => {
  const {channelId} = props
  const [listRes, setListRes] = useState<ListRes>({
    results: [],
    pre_timestamp: '' + new Date().getTime(),
  })
  
  useEffect(() => {
    const getList = async () => {
      try {
        const res = await fetchArticleListAPI({
          channel_id: channelId,
          timestamp: '' + new Date().getTime(),
        })
        setListRes({
          results: res.data.data.results,
          pre_timestamp: res.data.data.pre_timestamp,
        })
      } catch (error) {
        throw new Error(error as string)
      }
    }
    
    getList()
  }, [channelId])

  // 上拉加载触发的必要条件 1.hasMore=true 2.小于thresold
  // 标记当前是否还有新数据
  const [hasMore, setHasMore] = useState(true)
  // 加载下一页函数
  const loadMore = async () => {
    try {
      const res = await fetchArticleListAPI({
        channel_id: channelId,
        timestamp: listRes.pre_timestamp
      })
      setListRes({
        // 拼接新数据 + 存入下一次发送请求的时间戳 时间戳用于后端获取新数据
        results: [...listRes.results, ...res.data.data.results],
        pre_timestamp: res.data.data.pre_timestamp,
      })
      // 停止监听
      if (res.data.data.results.length === 0) {
        setHasMore(false)
      }
    } catch (error) {
      throw new Error(error as string)
    }
  }

  const navigate =useNavigate()
  const goToDetail = (id:string) => {
    navigate(`/detail?id=${id}`)
  }

  return (
    <>
      <List>
        {listRes.results.map((item) => (
          <List.Item 
            onClick={()=> goToDetail(item.art_id)}
            key={item.art_id}
            prefix={
              <Image
                src={item.cover.images?.[0]}
                style={{ borderRadius: 20 }}
                fit="cover"
                width={40}
                height={40}
              />
            }
            description={item.pubdate}
            >
            {item.title}
          </List.Item>
        ))}
      </List>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10}></InfiniteScroll>
    </>
)
}

export default HomeList